package com.ky.manage.utils;

import android.app.Activity;
import android.content.Context;
import android.net.Network;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;

import com.ky.manage.BaseApplication;
import com.ky.manage.BuildConfig;
import com.ky.manage.R;
import com.ky.manage.activityLifecycle.ActivityManagerUtil;
import com.ky.manage.constant.OverallData;
import com.ky.manage.permission.AndPermissionUtils;
import com.ky.manage.ui.CustomPopWindow;
import com.ky.manage.ui.dialog.CommonDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.IFloatWindow;
import com.yhao.floatwindow.MoveType;
import com.yhao.floatwindow.ViewStateListener;
import com.youth.banner.Banner;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 工具类
 */
public class ZyUtils {
    private static ZyUtils mInstance;
    private NetworkUtils networkUtils;

    private ZyUtils() {
        networkUtils = new NetworkUtils();
    }

    public static ZyUtils getInstance() {
        if (mInstance == null) {
            synchronized (ZyUtils.class) {
                if (mInstance == null) {
                    mInstance = new ZyUtils();
                }
            }
        }
        return mInstance;
    }

    public NetworkUtils getNetworkUtils() {
        return networkUtils;
    }

    public boolean isNetConnected() {
        boolean isConnected = networkUtils.isConnected();
        if (!isConnected) {
            ToastUtils.showRoundRectToast("网络不可用, 请检查网络");
        }
        return isConnected;
    }

    public void registerNetworkCallback() {
        networkUtils.registerNetworkCallback(new NetworkUtils.NetworkConnectInterface() {
            @Override
            public void onAvailable(Network network) {
                //网络可用
            }

            @Override
            public void onLost(Network network) {
                //网络不可用
                ToastUtils.showRoundRectToast("网络不可用, 请检查网络");
            }
        });
    }

    private CustomPopWindow mCustomPopWindow;

    /**
     * 展示弹层
     *
     * @param activity
     * @param resLayoutId
     * @param dismissListener
     * @param xOff
     * @param yOff
     */
    public void showCustomPop(Activity activity, View targetView, int resLayoutId,
                              PopupWindow.OnDismissListener dismissListener, int xOff, int yOff) {
        showCustomPop(activity, targetView, resLayoutId, dismissListener, ViewGroup.LayoutParams.WRAP_CONTENT,
                xOff, yOff);
    }

    public void showCustomPop(Activity activity, View targetView, int resLayoutId,
                              PopupWindow.OnDismissListener dismissListener,
                              int width, int xOff, int yOff) {
        if (ActivityManagerUtil.getInstance().isActivityDestroy(activity) || null == targetView
                || resLayoutId <= 0) {
            return;
        }
        //创建并显示popWindow
        View contentView = LayoutInflater.from(activity).inflate(resLayoutId, null);
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(activity)
                .setView(contentView)
                .setBgDarkAlpha(0.8f)
                .enableBackgroundDark(true)
                .size(width, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .setOnDismissListener(() -> {
                    if (null != dismissListener) {
                        dismissListener.onDismiss();
                    }
                })
                .create()
                .showAsDropDown(targetView, xOff, yOff);
    }

    /**
     * 展示弹层
     *
     * @param activity
     * @param contentView
     * @param dismissListener
     * @param xOff
     * @param yOff
     */
    public void showCustomPop(Activity activity, View targetView, View contentView,
                              PopupWindow.OnDismissListener dismissListener, int xOff, int yOff) {
        showCustomPop(activity, targetView, contentView, dismissListener,
                ViewGroup.LayoutParams.WRAP_CONTENT, xOff, yOff);
    }

    /**
     * pop
     * @param activity
     * @param targetView
     * @param contentView
     * @param dismissListener
     * @param width
     * @param xOff
     * @param yOff
     */
    public void showCustomPop(Activity activity, View targetView, View contentView,
                              PopupWindow.OnDismissListener dismissListener, int width, int xOff, int yOff) {
        if (ActivityManagerUtil.getInstance().isActivityDestroy(activity) || null == targetView
                || contentView == null) {
            return;
        }
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(activity)
                .setView(contentView)
                .setBgDarkAlpha(0.8f)
                .enableBackgroundDark(true)
                .size(width, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .setOnDismissListener(() -> {
                    if (null != dismissListener) {
                        dismissListener.onDismiss();
                    }
                })
                .create()
                .showAsDropDown(targetView, xOff, yOff);
    }

    /**
     * 关闭弹层
     */
    public void hideCustomPop() {
        if (null != mCustomPopWindow) {
            mCustomPopWindow.dismiss();
            mCustomPopWindow = null;
        }
    }

    private CommonDialog mImgPreviewDialog = null;
    private Banner banner;

    /**
     * 已上传图片预览
     * @param fragmentActivity
     * @param urlList
     * @param curPosition
     */
    public void previewImgs(FragmentActivity fragmentActivity, List<String> urlList, int curPosition) {
        if (null == fragmentActivity || ActivityManagerUtil.getInstance().isActivityDestroy(fragmentActivity)
                || null == urlList || urlList.isEmpty()) {
            return;
        }
        PictureSelector.create(fragmentActivity)
                .externalPicturePreview(curPosition, getPreviewMediaList(urlList), 0);
//        OverallData.hd.post(() -> {
//            if (null == mImgPreviewDialog) {
//                WeakReference<FragmentActivity> activityWeakReference = new WeakReference<>(fragmentActivity);
//                mImgPreviewDialog = CommonDialog.create(activityWeakReference.get().getSupportFragmentManager())
//                        .setLayoutRes(R.layout.dialog_img_preview)
//                        .setViewListener(((v, baseDialog) -> {
//                            if (null == activityWeakReference || null == activityWeakReference.get()
//                                    || activityWeakReference.get().isFinishing()) {
//                                return;
//                            }
//                            banner = v.findViewById(R.id.banner);
//                            banner.setImages(urlList);
//                            banner.setImageLoader(new GlideImageLoader());
//                            //设置指示器的位置，小点点，左中右。
//                            banner.setIndicatorGravity(BannerConfig.CENTER)
//                                    //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
//                                    .setOnBannerListener(position -> {
//                                        //点击
//                                        mImgPreviewDialog.dismissAllowingStateLoss();
//                                    })
//                                    //必须最后调用的方法，启动轮播图。
//                                    .start();
//
//                        }))
//                        .setOnDismissListener(dialog -> {
//                            if (null != banner) {
//                                banner.releaseBanner();
//                                banner = null;
//                            }
//                            mImgPreviewDialog = null;
//                        })
//                        .setDialogWidth(ScreenUtils.getScreenW()*4/5)
//                        .setDialogWidth(ScreenUtils.getScreenH()*4/5)
//                        .setDialogAnimationRes(R.style.Center_Zoom_Dialog)
//                        .setGravity(Gravity.CENTER)
//                        .setDimAmount(0.2f)
//                        .setCancelOutside(true)
//                        .setKeyBackDismiss(true)
//                        .setTag("ImgPreviewDialog");
//            }
//            if (null != mImgPreviewDialog && mImgPreviewDialog.isShowing()) {
//                return;
//            }
//            mImgPreviewDialog.show();
//        });
    }

    private List<LocalMedia> getPreviewMediaList(List<String> urlList) {
        List<LocalMedia> localMediaList = new ArrayList<>();
        for (String url : urlList) {
            if (!TextUtils.isEmpty(url)) {
                LocalMedia media = new LocalMedia();
                media.setPath(url);
                localMediaList.add(media);
            }
        }
        return localMediaList;
    }

    private CommonDialog mLoadingDialog = null;
    private ImageView mProgressIv;
    /**
     * 显示loading
     *
     * @param fragmentActivity
     * @param dialogDesc
     */
    public void showLoadingDialog(FragmentActivity fragmentActivity, String dialogDesc) {
        if (null == fragmentActivity || ActivityManagerUtil.getInstance().isActivityDestroy(fragmentActivity)) {
            return;
        }
        OverallData.hd.post(() -> {
            if (null == mLoadingDialog) {
                WeakReference<FragmentActivity> activityWeakReference = new WeakReference<>(fragmentActivity);
                mLoadingDialog = CommonDialog.create(activityWeakReference.get().getSupportFragmentManager())
                        .setLayoutRes(R.layout.layout_lx_loading)
                        .setViewListener(((v, baseDialog) -> {
                            if (null == activityWeakReference || null == activityWeakReference.get()
                                    || activityWeakReference.get().isFinishing()) {
                                return;
                            }
                            mProgressIv = v.findViewById(R.id.progress_iv);
                            TextView descTv = v.findViewById(R.id.progress_desc_tv);
                            descTv.setText(TextUtils.isEmpty(dialogDesc) ? "加载中, 请稍候..." :
                                    dialogDesc);
                            mProgressIv.startAnimation(AnimationUtils.loadAnimation(OverallData.app,
                                    R.anim.zy_loading));
                        }))
                        .setOnDismissListener(dialog -> {
                            if (null != mProgressIv && mProgressIv.isAttachedToWindow()) {
                                mProgressIv.clearAnimation();
                                mProgressIv = null;
                            }
                            mLoadingDialog = null;
                        })
                        .setDialogWidth(ScreenUtils.dp2px(300))
                        .setDialogAnimationRes(R.style.Center_Zoom_Dialog)
                        .setGravity(Gravity.CENTER)
                        .setDimAmount(0.2f)
                        .setCancelOutside(false)
                        .setKeyBackDismiss(false)
                        .setTag("LoadingDialog");
            }
            if (null != mLoadingDialog && mLoadingDialog.isShowing()) {
                return;
            }
            mLoadingDialog.show();
        });
    }

    /**
     * 隐藏loading对话框
     */
    public void hideLoadingDialog() {
        OverallData.hd.post(() -> {
            if (null != mLoadingDialog && mLoadingDialog.isShowing()) {
                mLoadingDialog.dismissAllowingStateLoss();
                mLoadingDialog = null;
            }
        });
    }

    public void hideFloatWindow(String floatTag) {
        if (TextUtils.isEmpty(floatTag)) {
            return;
        }
        try {
            if (FloatWindow.get(floatTag) != null) {
                FloatWindow.destroy(floatTag);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 展示查看日志浮窗
     */
    public void showSeeLogEntryFloatWindow(final Activity activity) {
        if (activity instanceof FragmentActivity) {
            if (BuildConfig.DEBUG) {
                IFloatWindow floatWindow = FloatWindow.get(SEE_LOG_ENTRY_FLOAT_WINDOW_TAG);
                if (null != floatWindow && floatWindow.isShowing()) {
                    return;
                }
                AndPermissionUtils.getInstance().requestAlertWindowPermission(activity, true,
                        new AndPermissionUtils.PermissionRequestListener() {
                            @Override
                            public void onGranted() {
                                //授权成功, 显示浮窗
                                initSeeLogFloatEntry((FragmentActivity)activity);
                            }

                            @Override
                            public void onDenied(List<String> data) {
                            }
                        });
            }
        }
    }

    public static final String SEE_LOG_ENTRY_FLOAT_WINDOW_TAG = "see_log_float";
    /**
     * 查看日志浮窗位置
     */
    private int mSeeLogEntryFloatX = -1, mSeeLogEntryFloatY = -1;
    /**
     * log结果列表弹框
     */
    private CommonDialog mLogListDialog;
    private TextView mLogTv;
    private StringBuffer mLogListSb = new StringBuffer();

    /**
     * 初始化查看日志浮窗
     * @param activity
     */
    private void initSeeLogFloatEntry(FragmentActivity activity) {
        if (BuildConfig.DEBUG) {
            if (FloatWindow.get(SEE_LOG_ENTRY_FLOAT_WINDOW_TAG) == null) {
                Context context = BaseApplication.getContext();
                View view = LayoutInflater.from(context).inflate(R.layout.layout_entry_float_window, null);
                TextView entryTv = view.findViewById(R.id.entry_tv);
                entryTv.setText("查看日志");
                view.setOnClickListener(v -> {
                    //展示测试入口
                    showLogListDialog(activity);
                });
                FloatWindow
                        .with(context)
                        .setView(view)
                        //设置控件初始位置
                        .setX(mSeeLogEntryFloatX >= 0 ? mSeeLogEntryFloatX : ScreenUtils.dp2px(0f))
                        .setY(mSeeLogEntryFloatY >= 0 ? mSeeLogEntryFloatY : ScreenUtils.getScreenH() / 3)
                        .setDesktopShow(true)
                        .setMoveType(MoveType.slide)
                        .setViewStateListener(new ViewStateListener() {
                            @Override
                            public void onPositionUpdate(int x, int y) {
                                IFloatWindow floatWindow = FloatWindow.get(SEE_LOG_ENTRY_FLOAT_WINDOW_TAG);
                                if (null != floatWindow) {
                                    int screenH = ScreenUtils.getScreenH(), screenW = ScreenUtils.getScreenW(), floatViewH = floatWindow.getView().getHeight();
                                    boolean needUpdateX = false, needUpdateY = false;
                                    if (x < 0) {
                                        x = 0;
                                        needUpdateX = true;
                                    }
                                    if (x > screenW) {
                                        x = screenW;
                                        needUpdateX = true;
                                    }
                                    if (y < 0) {
                                        y = 0;
                                        needUpdateY = true;
                                    }
                                    if (y > (screenH - floatViewH)) {
                                        y = screenH - floatViewH;
                                        needUpdateY = true;
                                    }
                                    if (needUpdateX) {
                                        floatWindow.updateX(x);
                                    }
                                    if (needUpdateY) {
                                        floatWindow.updateY(y);
                                    }
                                    mSeeLogEntryFloatX = x;
                                    mSeeLogEntryFloatY = y;
                                }
                            }

                            @Override
                            public void onShow() {

                            }

                            @Override
                            public void onHide() {

                            }

                            @Override
                            public void onDismiss() {

                            }

                            @Override
                            public void onMoveAnimStart() {

                            }

                            @Override
                            public void onMoveAnimEnd() {

                            }

                            @Override
                            public void onBackToDesktop() {

                            }
                        })
                        .setTag(SEE_LOG_ENTRY_FLOAT_WINDOW_TAG)
                        .build();
            }
            FloatWindow.get(SEE_LOG_ENTRY_FLOAT_WINDOW_TAG).show();
        }
    }


    /**
     * 显示log结果列表弹框
     * @param activity
     * @return
     */
    private void showLogListDialog(FragmentActivity activity) {
        if (null == mLogListDialog) {
            WeakReference<FragmentActivity> activityWeakReference = new WeakReference<>(activity);
            mLogListDialog = CommonDialog.create(activityWeakReference.get().getSupportFragmentManager())
                    .setLayoutRes(R.layout.dialog_log_result_list)
                    .setViewListener(((v, baseDialog) -> {
                        if (null == activityWeakReference || null == activityWeakReference.get()
                                || activityWeakReference.get().isFinishing()) {
                            return;
                        }
                        mLogTv = v.findViewById(R.id.log_list_tv);
                        mLogTv.setText(mLogListSb.toString());
                    }))
                    .setOnDismissListener(dialog -> {
                        //对话框关闭
                        mLogListDialog = null;
                    })
                    .setDialogAnimationRes(R.style.Center_Zoom_Dialog)
                    .setDialogWidth(ScreenUtils.getScreenW() * 5 / 6)
                    .setDialogHeight(ScreenUtils.getScreenH() * 5 / 6)
                    .setGravity(Gravity.CENTER)
                    .setDimAmount(0.2f)
                    .setCancelOutside(true)
                    .setTag("LogListDialog");
        }
        if (null != mLogListDialog && mLogListDialog.isShowing()) {
            return;
        }
        mLogListDialog.show();
    }

    /**
     * 更新日志
     *
     * @param tag
     * @param content
     */
    public void insertLog(String tag, String content) {
        if (BuildConfig.DEBUG) {
            Log.d("zhaoyan", "tag = " + tag + ", thread = " + Thread.currentThread().getName() + ", content = " + content);
            OverallData.hd.post(() -> {
                mLogListSb.append(TimeUtil.getAllDate(System.currentTimeMillis())).append(": ")
                        .append(tag).append("_").append(content).append("\n\n");
                if (null != mLogListDialog && mLogListDialog.isShowing() && null != mLogTv) {
                    mLogTv.setText(mLogListSb.toString());
                }
            });
        }
    }
}
